package com.jiexinyun.service.android.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jiexinyun.constants.ConstantsC;
import com.jiexinyun.constants.RedisLockKeys;
import com.jiexinyun.dao.*;
import com.jiexinyun.dto.request.androidworktask.*;
import com.jiexinyun.dto.response.AjaxResult;
import com.jiexinyun.dto.response.worktask.WorkTaskTan;
import com.jiexinyun.entity.JldwEntity;
import com.jiexinyun.entity.PpPlanEntity;
import com.jiexinyun.entity.PpPlanGxEntity;
import com.jiexinyun.entity.RytreeEntity;
import com.jiexinyun.entity.worktask.WorkTaskEntity;
import com.jiexinyun.entity.worktask.WorkTaskMxEntity;
import com.jiexinyun.entity.worktask.WorkTaskRegEntity;
import com.jiexinyun.exception.BusinessException;
import com.jiexinyun.ftp.FTPDirectoryLister;
import com.jiexinyun.ftp.FtpUtil;
import com.jiexinyun.service.android.PublicWorkTaskService;
import com.jiexinyun.utils.CodeUtils;
import com.jiexinyun.utils.CommonUtils;
import com.jiexinyun.utils.CustomizDateUtils;
import com.jiexinyun.utils.lock.RedisLockUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class PublicWorkTaskServiceImpl implements PublicWorkTaskService {

    @Autowired
    private PpPlanMapper ppPlanMapper;

    @Autowired
    private PpPlanGxMapper ppPlanGxMapper;

    @Autowired
    private PpScpcPlanMxMapper ppScpcPlanMxMapper;

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    @Autowired
    private WorkTaskMapper workTaskMapper;

    @Autowired
    private WorkTaskMxMapper workTaskMxMapper;

    @Autowired
    private WorkTaskRegMapper workTaskRegMapper;

    @Autowired
    private RytreeMapper rytreeMapper;

    @Autowired
    private FTPDirectoryLister ftpDirectoryLister;

    @Autowired
    private JldwMapper jldwMapper;

    @Autowired
    private FtpUtil ftpUtil;

    /**
     * 根据码值查询生产任务
     * @param req
     * @return
     */
    @Override
    public AjaxResult queryWorkTaskByCode(QueryWorkTaskByCodeReq req) {

        log.info("根据码值查询生产任务请求:{}", req);

        //验证员工ID
        Integer ryId = req.getRyId();
        RytreeEntity wiseRytreeEntity = rytreeMapper.selectById(ryId);
        if (CommonUtils.isNull(wiseRytreeEntity)) {
            return AjaxResult.error("机台员工信息不正确，请重新登录！");
        }

        //码值就是批号
        String ph = req.getCode();

//        CodeUtils.getPhByCode(code);
//        String gongbuma = CodeUtils.getGongbumaByCode(code);

        if (CommonUtils.isBlank(ph)) {
            return AjaxResult.error("二维码:"+ph+"，没有批号内容，请核实！");
        }

        LambdaQueryWrapper<PpPlanEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PpPlanEntity::getPh, ph);
        List<PpPlanEntity> wisePpPlanList = ppPlanMapper.selectList(lambdaQueryWrapper);

        if (CommonUtils.isEmpty(wisePpPlanList)) {
            return AjaxResult.error("批号:"+ph+"，没有对应的生产指令，请核实！");
        }

        if (wisePpPlanList.size() > 1) {
            return AjaxResult.error("批号:"+ph+"，对应的生产指令过多，请核实！");
        }

        PpPlanEntity ppPlan = wisePpPlanList.get(0);

        WorkTaskTan tan = new WorkTaskTan();

        BeanUtils.copyProperties(ppPlan, tan);
        tan.setHwid(ppPlan.getHwid());
        tan.setHwmc(ppPlan.getHwmc());
        tan.setGg(ppPlan.getGg());
        tan.setWlCz(ppPlan.getWlCz());
        tan.setPh(ppPlan.getPh());
        tan.setWlBz(ppPlan.getWlBz());
        tan.setWlBmcl(ppPlan.getWlBmcl());
        tan.setWlYdxn(ppPlan.getWlYdxn());
        tan.setJldw(ppPlan.getJldw());
        tan.setJhSl(ppPlan.getDhSl());

        String jldwDes = "";
        JldwEntity jldwEntity = jldwMapper.selectById(ppPlan.getJldw());
        if (jldwEntity != null) {
            jldwDes = jldwEntity.getMc();
        }
        tan.setJldwDes(jldwDes);

        tan.setJhTime(ppPlan.getDhTime());

        return AjaxResult.success(tan);
    }

    /**
     * 查询机台任务列表
     * @param req
     * @return
     */
    @Override
    public AjaxResult queryWorkTaskList(WorkTaskListReq req) {

        log.info("列表查询请求:{}", req);

        //先验证员工ID
        Integer ryId = req.getRyId();
        RytreeEntity wiseRytreeEntity = rytreeMapper.selectById(ryId);
        if (CommonUtils.isNull(wiseRytreeEntity)) {
            return AjaxResult.error("机台员工信息不正确，请重新登录！");
        }

        LambdaQueryWrapper<WorkTaskEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WorkTaskEntity::getRyId, ryId);
        lambdaQueryWrapper.eq(WorkTaskEntity::getStatus, 1);
        lambdaQueryWrapper.orderByAsc(WorkTaskEntity::getScpcSx);

        List<WorkTaskEntity> list = workTaskMapper.selectList(lambdaQueryWrapper);
        return AjaxResult.success(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveWorkTask(SaveWorkTaskReq req) throws Exception {

        log.info("根据码值查询生产任务请求:{}", req);

        //同一时间只能入一次防止多人同时录入 数据错乱
        String key = ConstantsC.MAIN_BODY + RedisLockKeys.WISE_WORK_TASK_ADD.name();
        if(RedisLockUtils.tryLock(key)) {
            try {
                //验证员工ID
                Integer ryId = req.getRyId();
                RytreeEntity wiseRytreeEntity = rytreeMapper.selectById(ryId);
                if (CommonUtils.isNull(wiseRytreeEntity)) {
                    return AjaxResult.error("机台员工信息不正确，请重新登录！");
                }

                String ph = req.getCode();//码值

                //获取码值和工步码
                if(CommonUtils.isBlank(ph)){
                    return AjaxResult.error("二维码:"+ph +"，没有批号内容，请核实！");
                }

                LambdaQueryWrapper<PpPlanEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(PpPlanEntity::getPh, ph);
                List<PpPlanEntity> ppPlanList = ppPlanMapper.selectList(lambdaQueryWrapper);

                if (CommonUtils.isEmpty(ppPlanList)) {
                    return AjaxResult.error("批号:"+ph+"，没有对应的生产指令，请核实！");
                }

                if (ppPlanList.size() > 1) {
                    return AjaxResult.error("批号:"+ph+"，对应的生产指令过多，请核实！");
                }

                PpPlanEntity ppPlan = ppPlanList.get(0);

                //查询生产指令-工艺路线
                Integer ppPlanId = ppPlan.getId();
                LambdaQueryWrapper<PpPlanGxEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<PpPlanGxEntity>();
                lambdaQueryWrapper1.eq(PpPlanGxEntity::getPid, ppPlanId);
                List<PpPlanGxEntity> ppPlanGxList = ppPlanGxMapper.selectList(lambdaQueryWrapper1);

                if (CommonUtils.isEmpty(ppPlanGxList)) {
                    return AjaxResult.error("批号:"+ph+"，没有对应的生产指令，请核实！");
                }


                WorkTaskEntity workTaskEntity = new WorkTaskEntity();

                BeanUtils.copyProperties(ppPlan, workTaskEntity);

                workTaskEntity.setWisePpPlanId(ppPlanId);
//                workTaskEntity.setGxId(wisePpPlan.getGxId());
//                workTaskEntity.setGxName(wisePpPlan.getGxName());
                workTaskEntity.setHwid(ppPlan.getHwid());
                workTaskEntity.setHwmc(ppPlan.getHwmc());
                workTaskEntity.setGg(ppPlan.getGg());
                workTaskEntity.setPh(ppPlan.getPh());
                workTaskEntity.setWlBz(ppPlan.getWlBz());
                workTaskEntity.setWlBmcl(ppPlan.getWlBmcl());
                workTaskEntity.setWlYdxn(ppPlan.getWlYdxn());
                workTaskEntity.setJldw(ppPlan.getJldw());

                workTaskEntity.setJhSl(ppPlan.getDhSl());

                String jldwDes = "";
                JldwEntity wiseJldwEntity = jldwMapper.selectById(ppPlan.getJldw());
                if (wiseJldwEntity != null) {
                    jldwDes = wiseJldwEntity.getMc();
                }
                workTaskEntity.setJldwDes(jldwDes);

                workTaskEntity.setJhTime(ppPlan.getDhTime());
                workTaskEntity.setComment(ppPlan.getComment());

                workTaskEntity.setRyId(ryId);
                workTaskEntity.setStatus((short) 1);

                //生产排程排序
                Integer scpcSx = workTaskMapper.findScpcSxSort();
                AtomicInteger atomicInteger = new AtomicInteger(scpcSx);
                workTaskEntity.setScpcSx(atomicInteger.incrementAndGet());

                LambdaQueryWrapper<WorkTaskEntity> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(WorkTaskEntity::getPh, ph);
                List<WorkTaskEntity> list = workTaskMapper.selectList(lambdaQueryWrapper2);
                if (CommonUtils.isNotEmpty(list)) {
                    throw new BusinessException("批号："+ph+"，已经增加过生产任务，请核实！");
                }

                int f = workTaskMapper.insert(workTaskEntity);

                if (f < 0) {
                    throw new BusinessException("批号："+ph+"，保存失败！");
                }

                for (PpPlanGxEntity wisePpPlanGx : ppPlanGxList) {
                    WorkTaskMxEntity workTaskMxEntity = new WorkTaskMxEntity();

                    workTaskMxEntity.setPid(workTaskEntity.getId());

                    workTaskMxEntity.setGxId(wisePpPlanGx.getGxId());
                    workTaskMxEntity.setGxName(wisePpPlanGx.getGxName());

                    workTaskMxEntity.setGg(ppPlan.getGg());
                    workTaskMxEntity.setWlCz(ppPlan.getWlCz());
                    workTaskMxEntity.setPh(ppPlan.getPh());
                    workTaskMxEntity.setWlBz(ppPlan.getWlBz());
                    workTaskMxEntity.setWlBmcl(ppPlan.getWlBmcl());
                    workTaskMxEntity.setWlYdxn(ppPlan.getWlYdxn());
                    workTaskMxEntity.setJldw(ppPlan.getJldw());


                    int f2 = workTaskMxMapper.insert(workTaskMxEntity);
                    if (f2 < 0) {
                        throw new BusinessException("批号："+ph+"，保存失败！");
                    }
                }
                return AjaxResult.error();
            } catch (Exception e) {
                log.error("", e);
            } finally {
                RedisLockUtils.unlock();
            }
        }
        return AjaxResult.error("保存失败");
    }

    @Override
    public AjaxResult queryWorkTaskRegByCode(QueryWorkTaskRegByCodeReq req) {

        log.info("根据工步码查询生产任务请求:{}", req);
        //不做那么麻烦，只做数据查询，验证员工编号，员工编号数据在万思表 rytree 表中，返回给安卓

        String code = req.getCode();

        //验证员工ID
        Integer ryId = req.getRyId();
        RytreeEntity wiseRytreeEntity = rytreeMapper.selectById(ryId);
        if (CommonUtils.isNull(wiseRytreeEntity)) {
            return AjaxResult.error("机台员工信息不正确，请重新登录！");
        }

        //获取码值和工步码
        String ph = CodeUtils.getPhByCode(code);
        String gongbuma = CodeUtils.getGongbumaByCode(code);

        LambdaQueryWrapper<WorkTaskEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WorkTaskEntity::getPh, ph);
//        lambdaQueryWrapper.eq(WorkTaskEntity::getGongbuma, gongbuma);
        lambdaQueryWrapper.and(wq -> wq.eq(WorkTaskEntity::getStatus, 1).or().eq(WorkTaskEntity::getStatus, 2));
        List<WorkTaskEntity> list = workTaskMapper.selectList(lambdaQueryWrapper);
        if (CommonUtils.isEmpty(list)) {
            return AjaxResult.error("批号："+ph+"，工步码："+gongbuma+"没有已经生产的生产任务，请核实！");
        }

        if (list.size() > 1) {
            return AjaxResult.error("批号："+ph+"，工步码："+gongbuma+"对应的已经生产的生产任务过多，请核实！");
        }

        WorkTaskEntity workTaskEntity = list.get(0);
        if (!ryId.equals(workTaskEntity.getRyId())) {
            return AjaxResult.error("不是本人生产的任务，不能查看！");
        }

        WorkTaskTan tan = new WorkTaskTan();
        BeanUtils.copyProperties(workTaskEntity, tan);
        return AjaxResult.success(tan);

//
//
//
//        //根据工步码查询工艺路线
//        LambdaQueryWrapper<WisePpPlanGxEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(WisePpPlanGxEntity::getGongbuma, gongbuma);
//        List<WisePpPlanGxEntity> wisePpPlanGxEntities = wisePpPlanGxMapper.selectList(lambdaQueryWrapper);
//        if (CommonUtils.isEmpty(wisePpPlanGxEntities)) {
//            return AjaxResult.error("工步码:"+gongbuma+"不存在，请核实！");
//        }
//
//        if (wisePpPlanGxEntities.size() > 1) {
//            return AjaxResult.error("工步码:"+gongbuma+"存在多条，请核实！");
//        }
//
//        WisePpPlanGxEntity wisePpPlanGxEntity = wisePpPlanGxEntities.get(0);
//
//        //查询生产指令主表
//        LambdaQueryWrapper<WisePpPlanEntity> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper2.eq(WisePpPlanEntity::getId, wisePpPlanGxEntity.getPid());
//
//        WisePpPlanEntity wisePpPlanEntity = wisePpPlanMapper.selectById(lambdaQueryWrapper2);
//        if(CommonUtils.isNull(wisePpPlanEntity)) {
//            return AjaxResult.error("工步码:"+gongbuma+"没有对应生产指令-工艺路线，请核实！");
//        }
    }

    @Override
    public AjaxResult queryWorkTaskRegList(WorkTaskRegListReq req) {

        log.info("查询请求:{}", req);

        //先验证员工ID
        Integer ryId = req.getRyId();
        RytreeEntity rytreeEntity = rytreeMapper.selectById(ryId);
        if (CommonUtils.isNull(rytreeEntity)) {
            return AjaxResult.error("机台员工信息不正确，请重新登录！");
        }

        //获取当天时间 yyyy-MM-dd
        String outputDateStr = CustomizDateUtils.yyyy_MM_ddStrCur();

        LambdaQueryWrapper<WorkTaskEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WorkTaskEntity::getRyId, ryId);
        lambdaQueryWrapper.eq(WorkTaskEntity::getOutputDateStr, outputDateStr);
        lambdaQueryWrapper.eq(WorkTaskEntity::getStatus, 2);

        List<WorkTaskEntity> list = workTaskMapper.selectList(lambdaQueryWrapper);

        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult goWorkTaskReg(GoWorkTaskReq req) {

        log.info("上报任务产出请求:{}", req);

        //先验证员工ID
        Integer ryId = req.getRyId();
        String gongbuma = req.getGongbuma();
        RytreeEntity rytreeEntity = rytreeMapper.selectById(ryId);
        if (CommonUtils.isNull(rytreeEntity)) {
            return AjaxResult.error("机台员工信息不正确，请重新登录！");
        }

        //先查询有没有导入过生产登记
        LambdaQueryWrapper<WorkTaskRegEntity> workTaskRegWrapper = new LambdaQueryWrapper<>();
        workTaskRegWrapper.eq(WorkTaskRegEntity::getGongbuma, gongbuma);
        List<WorkTaskRegEntity> list = workTaskRegMapper.selectList(workTaskRegWrapper);

        if (CommonUtils.isNotEmpty(list)) {
            return AjaxResult.error("工步码:"+gongbuma+"已经上报过，不能再进行上报完工！");
        }

        //根据工步码查询工艺路线
        LambdaQueryWrapper<PpPlanGxEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PpPlanGxEntity::getGongbuma, gongbuma);
        List<PpPlanGxEntity> ppPlanGxEntities = ppPlanGxMapper.selectList(lambdaQueryWrapper);
        if (CommonUtils.isEmpty(ppPlanGxEntities)) {
            return AjaxResult.error("工步码:"+gongbuma+"不存在，请核实！");
        }

        if (ppPlanGxEntities.size() > 1) {
            return AjaxResult.error("工步码:"+gongbuma+"存在多条，请核实！");
        }

        PpPlanGxEntity ppPlanGxEntity = ppPlanGxEntities.get(0);

        //查询生产指令主表
        LambdaQueryWrapper<PpPlanEntity> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(PpPlanEntity::getId, ppPlanGxEntity.getPid());

        PpPlanEntity wisePpPlanEntity = ppPlanMapper.selectById(lambdaQueryWrapper2);
        if(CommonUtils.isNull(wisePpPlanEntity)) {
            return AjaxResult.error("工步码:"+gongbuma+"没有对应生产指令-工艺路线，请核实！");
        }

        WorkTaskRegEntity workTaskRegEntity = new WorkTaskRegEntity();
        workTaskRegEntity.setGongbuma(gongbuma);
        workTaskRegEntity.setWisePpPlanGxId(ppPlanGxEntity.getId());
        workTaskRegEntity.setWisePpPlanId(wisePpPlanEntity.getId());
        workTaskRegEntity.setPh(wisePpPlanEntity.getPh());
        workTaskRegEntity.setHwid(wisePpPlanEntity.getHwid());
        workTaskRegEntity.setHwmc(wisePpPlanEntity.getHwmc());
        workTaskRegEntity.setGg(wisePpPlanEntity.getGg());
        workTaskRegEntity.setWlCz(wisePpPlanEntity.getWlCz());
        workTaskRegEntity.setWlBz(wisePpPlanEntity.getWlBz());
        workTaskRegEntity.setWlDj(wisePpPlanEntity.getWlDj());
        workTaskRegEntity.setWlBmcl(wisePpPlanEntity.getWlBmcl());
        workTaskRegEntity.setJldw(wisePpPlanEntity.getJldw());
        workTaskRegEntity.setComment(wisePpPlanEntity.getComment());
        workTaskRegEntity.setDdh(wisePpPlanEntity.getDdh());
        workTaskRegEntity.setStatus((short) 1);
        workTaskRegEntity.setTransferStatus((short) 1);
        String regDateStr = CustomizDateUtils.yyyy_MM_ddStrCur();
        workTaskRegEntity.setRegDateStr(regDateStr);

        int f = workTaskRegMapper.insert(workTaskRegEntity);
        if(f > 0) {
            return AjaxResult.success(workTaskRegEntity);
        }
        return AjaxResult.error("上报产出登记失败");
    }

    /**
     * 查看图纸地址
     * 图纸是挂在nginx上的 nginx做了文件服务器
     * @return
     */
    @Override
    public AjaxResult tuzhi(QueryTuzhiReq req) {

        //根据客户名称和合同编号查询ftp
        //连接成功之后，返回图纸地址URL 例如：http://192.168.1.118:8084/20210000001.pdf
//        List<String> list = ftpDirectoryLister.listFiles("/工艺图纸/北方汽修/0014");

        //根据任务信息获取图纸路径
        //这里code就是编号
        String ph = req.getCode();
        String remotePath = "/工艺图纸/北方汽修/"+ph;
        List<String> list = ftpDirectoryLister.listFiles(remotePath);
        /**
         * List<String> list = ftpUtil.listFiles(remotePath);
         */
        return AjaxResult.success(list);
    }

    public static void main(String[] args) throws InterruptedException {
//        AtomicReference<String> r = new AtomicReference<>();
//        CompletableFuture.supplyAsync(() -> {
//            return "异步线程结果";
//        }).thenAccept(result -> {
//            r.set(result);
//            System.out.println("外部获取：" + result);
//        });
//        System.out.println(r.get());

        BlockingQueue<String> queue = new LinkedBlockingQueue<>();

        new Thread(() -> {
            queue.offer("线程生产的数据");
        }).start();

        String result = queue.take(); // 阻塞获取
        System.out.println(result);

    }

}
